<template>
  <el-dialog v-model="dialogVisible" title="新增改造项目" width="50%" @close="onClose">
    <el-form ref="formRef" v-loading="formLoading" :model="form" :rules="rules">
      <el-card class="mt-1">
        <el-row :gutter="15">
          <el-button icon="el-icon-plus" type="primary" @click="handleAddItem">
            新增改造项
          </el-button>
        </el-row>

        <template v-for="(formItem, index) in form.items" :key="index">
          <div class="mt-5">
            <el-row :gutter="15">
              <el-col :span="10">
                <el-form-item
                  :label="'改造项目' + (index + 1)"
                  :prop="'items.' + index + '.category'"
                  :rules="rules.category"
                >
                  <el-cascader
                    v-model="formItem.category"
                    class="w-100"
                    :options="categoryOptions"
                    placeholder="改造项目"
                    clearable
                  />
                </el-form-item>
              </el-col>

              <el-col :span="10">
                <el-form-item
                  :label="'物品/材料明细' + (index + 1)"
                  :prop="'items.' + index + '.goods_detail'"
                  :rules="rules.goods_detail"
                >
                  <el-input v-model="formItem.goods_detail" clearable />
                </el-form-item>
              </el-col>

              <el-col :span="2">
                <el-button type="danger" circle icon="el-icon-minus" @click="onDeleteItem(index)" />
              </el-col>
            </el-row>

            <el-row :gutter="15">
              <el-col :span="10">
                <el-form-item
                  :label="'改造金额' + (index + 1)"
                  :prop="'items.' + index + '.money'"
                  :rules="rules.money"
                >
                  <el-input v-model="formItem.money" clearable />
                </el-form-item>
              </el-col>

              <el-col :span="10">
                <el-form-item
                  :label="'通过检查金额' + (index + 1)"
                  :prop="'items.' + index + '.check_money'"
                  :rules="rules.check_money"
                >
                  <el-input v-model="formItem.check_money" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirmClick">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { RevampFormItem, revampFormRules } from "./revamp-core";
import RevampAPI from "@/api/revamp";

defineOptions({
  name: "UserRevampFormDialog",
});

const formLoading = ref(false);
const formRef = ref();
const categoryOptions = ref<OptionType[]>([]);
const dialogVisible = ref(false);
const rules = ref(revampFormRules);

const form = ref({
  id: undefined as number | undefined,
  user_id: undefined as number | undefined,
  items: [RevampFormItem.empty()],
});

onMounted(() => {
  // 获取改造项目分类
  RevampAPI.getRevampCategoryOptions().then((options) => {
    categoryOptions.value = options;
  });
});

/**
 * @description 新增改造项
 */
function handleAddItem() {
  form.value.items.push(RevampFormItem.empty());
}

/**
 * @description 删除改造项
 * @param index
 * @returns
 */
function onDeleteItem(index: number) {
  form.value.items.splice(index, 1);
}

/**
 * @description 确定按钮点击事件
 */
async function onConfirmClick() {
  try {
    await formRef.value.validate((valid: boolean) => {
      if (valid) {
        RevampAPI.addRevamp(form.value).then(() => {
          ElMessage.success("添加改造项目成功");
        });
      } else {
        return false;
      }
    });
  } catch (error) {
    console.error("验证过程中发生错误", error);
  }
}

const onClose = () => {
  dialogVisible.value = false;
  form.value = {
    id: undefined,
    user_id: undefined,
    items: [RevampFormItem.empty()],
  };
};

/**
 * @description 打开添加弹窗
 * @param userId   用户ID
 * @returns
 */
const open = (userId: number) => {
  form.value.user_id = userId;
  dialogVisible.value = true;
};

// /**
//  * @description 打开编辑弹窗
//  * @param id
//  */
// const openEdit = (id: number) => {
//   form.value.id = id;
//   dialogVisible.value = true;
//   fetchData();
// };

// /**
//  * @description 获取数据
//  */
// const fetchData = () => {
//   if (!form.value.id) return;
//   formLoading.value = true;
//   RevampAPI.getDetail(form.value.id)
//     .then((res) => {
//       console.log(res);
//       form.value = {
//         id:res.id,
//         user_id:res.user_id,

//       }
//     })
//     .finally(() => {
//       formLoading.value = false;
//     });
// };

// 导出组件实例类型
export interface UserRevampFormDialogInstance {
  /** 打开弹窗 */
  open(userId: number): () => void;
}

defineExpose({
  open,
});
</script>
